package com.dinadi.yidi.ui.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.dinadi.yidi.R;
import com.dinadi.yidi.bean.CommentBean;
import com.dinadi.yidi.bean.VerificationCodeBean;
import com.dinadi.yidi.http.HttpListener;
import com.dinadi.yidi.http.interfaces.CommonInterface;
import com.dinadi.yidi.utils.BitmapUtils;
import com.dinadi.yidi.utils.EmptyUtils;
import com.dinadi.yidi.utils.FileUtils;
import com.dinadi.yidi.utils.ImageUtils;
import com.dinadi.yidi.utils.JsonUtil;
import com.dinadi.yidi.utils.SharePreferencesHelper;
import com.dinadi.yidi.utils.ToastUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.BitmapCallback;

import java.io.File;

import okhttp3.Call;

public class SplashActivity extends Activity {
    // 倒计时
    private TimeCount timeCount;
    private ImageView imageView;
    private RelativeLayout layout_time;
    private TextView tv_time;
    private String imgUrl, id, imgID;
    private int currentIndex;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        layout_time = (RelativeLayout) findViewById(R.id.layout_time);
        imageView = (ImageView) findViewById(R.id.start_page);
        tv_time = (TextView) findViewById(R.id.tv_time);
        imgID = SharePreferencesHelper.getInstance(SplashActivity.this).getString("imgID");

        boolean mFirst = isFirstEnter(SplashActivity.this, SplashActivity.this.getClass().getName());
        if (mFirst)
            mHandler.sendEmptyMessage(SWITCH_GUIDACTIVITY);
        Animation animation = new AlphaAnimation(0.2f, 1.0f);
        animation.setDuration(1000);
        animation.setFillAfter(true);// 保持动画最终状态
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {

                CommentBean bean = new CommentBean();
                CommonInterface verificationCodeInterface = new CommonInterface(SplashActivity.this, httpListener);
                verificationCodeInterface.getInterface("10007", JSON.toJSONString(bean));

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        AnimationSet set = new AnimationSet(true);
        set.addAnimation(animation);
        imageView.startAnimation(set);

    }

    //****************************************************************
    // 判断应用是否初次加载，读取SharedPreferences中的guide_activity字段
    //****************************************************************
    private static final String SHAREDPREFERENCES_NAME = "my_pref";
    private static final String KEY_GUIDE_ACTIVITY = "guide_activity";

    @SuppressLint("WorldReadableFiles")
    @SuppressWarnings("deprecation")
    private boolean isFirstEnter(Context context, String className) {
        if (context == null || className == null || "".equalsIgnoreCase(className)) return false;
        String mResultStr = context.getSharedPreferences(SHAREDPREFERENCES_NAME, 0)
                .getString(KEY_GUIDE_ACTIVITY, "");//取得所有类名 如 com.my.MainActivity
        return !mResultStr.equalsIgnoreCase("false");
    }

    //*************************************************
    // Handler:跳转至不同页面
    //*************************************************
    private final static int SWITCH_MAINACTIVITY = 1000;
    private final static int SWITCH_GUIDACTIVITY = 1001;
    @SuppressLint("HandlerLeak")
    public Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SWITCH_MAINACTIVITY:
                    Intent mIntent = new Intent();
                    mIntent.setClass(SplashActivity.this, MainActivity.class);
                    SplashActivity.this.startActivity(mIntent);
                    SplashActivity.this.finish();
                    break;
                case SWITCH_GUIDACTIVITY:
                    mIntent = new Intent();
                    mIntent.setClass(SplashActivity.this, GuideActivity.class);
                    SplashActivity.this.startActivity(mIntent);
                    SplashActivity.this.finish();
                    break;
            }
            super.handleMessage(msg);
        }
    };
    HttpListener httpListener = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            imgUrl = JsonUtil.getFieldValue(response, "imgUrl");
            id = JsonUtil.getFieldValue(response, "id");
            SharePreferencesHelper.getInstance(SplashActivity.this).putString("imgID", id);
            if (errCode.equals("0000")) {
                if (EmptyUtils.isNotEmpty(imgUrl)) {

                    if (imgID.equals(id)) {

                        if(FileUtils.fileIsExists(Environment.getExternalStorageDirectory() + "/out_photo/img_advertisement.png") ==true){
                            //直接显示本地图片
                            String s = Environment.getExternalStorageDirectory() + "/out_photo/img_advertisement.png";
                            Uri uri = Uri.fromFile(new File(s));
                            imageView.setImageURI(uri);
                        }else{
                            //保存图片并显示
                            downloadImage();
                        }
                    } else {
                        //保存图片并显示
                        downloadImage();
                    }
                    layout_time.setVisibility(View.VISIBLE);
                    timeCount = new TimeCount(4000, 1000);// 构造CountDownTimer对象
                    timeCount.start();// 开始计时

                } else {
                    gotoIntent();
                }


            }
        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
            ToastUtil.showToast("发送失败");
        }
    };

    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onFinish() {// 计时完毕时触发
            gotoIntent();
        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
            tv_time.setText(millisUntilFinished / 1000 + "s");
        }
    }

    private void gotoIntent() {
        startActivity(new Intent(SplashActivity.this, MainActivity.class));
        Intent intent = getIntent();
        String data = intent.getDataString();
        if (data != null) {
            String aa = data.substring(data.lastIndexOf("?") + 1);
            String bb = aa.substring(0, aa.indexOf("="));
            String cc = aa.substring(aa.lastIndexOf("=") + 1);
            if (bb.equals("showId")) {

                Intent intent1 = new Intent(SplashActivity.this, ExhibitionMatchActivity.class);
                intent1.putExtra("showId", cc);
                startActivity(intent1);

            } else if (bb.equals("productId")) {
                Intent intent1 = new Intent(SplashActivity.this, ProductDetailsActivity.class);
                intent1.putExtra("productId", cc);
                startActivity(intent1);
            }
        }
        finish();
    }


    /**
     * 开始下载图片
     */
    private void downloadImage() {
        OkHttpUtils.get()
                .url(imgUrl)
                .build()
                .connTimeOut(5000)
                .readTimeOut(5000)
                .execute(new BitmapCallback() {
                    @Override
                    public void onError(Call call, Exception e) {

                    }

                    @Override
                    public void onResponse(Bitmap response) {
                        FileUtils.savePhoto2(SplashActivity.this, response, new FileUtils.SaveResultCallback() {
                            @Override
                            public void onSavedSuccess() {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
//                                        Toast.makeText(SplashActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                                        String s = Environment.getExternalStorageDirectory() + "/out_photo/img_advertisement.png";
                                        Uri uri = Uri.fromFile(new File(s));
                                        imageView.setImageURI(uri);
                                    }
                                });
                            }

                            @Override
                            public void onSavedFailed() {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
//                                        Toast.makeText(SplashActivity.this, "保存失败", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        });
                    }
                });
    }
}
